package com.irdstudio.apicenter.console.controller.page;

import java.io.IOException;
import java.io.PrintWriter;
import java.sql.SQLException;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.UUID;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.RequestMapping;

import com.alibaba.fastjson.JSON;
import com.irdstudio.apicenter.console.controller.MacmsBaseAction;
import com.irdstudio.apicenter.console.service.template.SPageParamMainService;
import com.irdstudio.apicenter.console.service.template.SPageParamTagService;
import com.irdstudio.apicenter.console.service.template.SPageParamTradeService;
import com.irdstudio.apicenter.console.service.template.STemplateParamService;
import com.irdstudio.apicenter.frame.core.jdbc.JdbcBaseDAO;
import com.irdstudio.apicenter.frame.core.jdbc.container.PageInfo;
import com.irdstudio.apicenter.frame.maker.dm.SPageBase;
import com.irdstudio.apicenter.frame.maker.dm.SPageParamMain;
import com.irdstudio.apicenter.frame.maker.dm.SPageParamTag;
import com.irdstudio.apicenter.frame.maker.dm.SPageParamTrade;
import com.irdstudio.apicenter.frame.maker.dm.STemplateBase;
import com.irdstudio.apicenter.frame.maker.dm.STemplateParam;
import com.irdstudio.apicenter.frame.service.DataDicService;
import com.irdstudio.apicenter.frame.util.BeanUtils;

/**
 * 页面管理
 * 
 * @author zs.ligm
 * @version 1.0
 * @date 2015-06-27
 */
@Controller
@RequestMapping(value = "/pagemgr")
public class PageManagerAction extends MacmsBaseAction {
	@Autowired
	private SPageParamMainService sPageParamMainService;
	@Autowired
	private STemplateParamService sTemplateParamService;
	@Autowired
	private SPageParamTagService sPageParamTagService;
	@Autowired
	private SPageParamTradeService sPageParamTradeService;

	/**
	 * 页面列表
	 * 
	 * @param request
	 * @return
	 * @throws Exception
	 */
	@RequestMapping(value = "queryList")
	public String queryList(HttpServletRequest request) throws Exception {

		String pageid = "";
		String pagename = "";
		if (request.getParameter("pageid") != null) {
			pageid = request.getParameter("pageid");
		}
		if (request.getParameter("pagename") != null) {
			pagename = request.getParameter("pagename");
		}
		// 获取所有参数
		super.getAllRequestData(request);
		// 取得页面制作方式
		String pageMakeMode = request.getParameter("pageMakeMode");
		if (StringUtils.isEmpty(pageMakeMode)) {
			throw new Exception("必须传入页面制作方式(pageMakeMode)参数!");
		}

		// 查询数据并放入到上下文中
		PageInfo pageInfo = this.getPageInfo();
		String sql = "select a.*,b.template_name from s_page_base a,s_template_base b  where a.page_make_mode = ? and a.template_id = b.template_id   and a.page_id  like '%"
				+ pageid + "%'  and  a.page_name  like  '%" + pagename + "%'";
		super.context.addDataList("spbList", this.getTableModelDAO().queryList(
				sql, pageInfo, new Object[] { pageMakeMode }));
		super.context.addPageInfo("spbList", pageInfo);

		request.setAttribute("pageMakeMode", pageMakeMode);
		// 将数据上下文放到属性中
		request.setAttribute("context", super.context);

		return "admin/pageList";
	}

	/**
	 * 创建页面
	 * 
	 * @param request
	 * @return
	 * @throws Exception
	 */
	@RequestMapping(value = "create")
	public String create(HttpServletRequest request) throws Exception {
		// 查询数据并放入到上下文中
		String moduleid = request.getParameter("moduleid");
		String sql = "select b.TEMPLATE_ID,b.TEMPLATE_NAME  from s_template_base b ";
		JdbcBaseDAO baseDao = BeanUtils.getBean(JdbcBaseDAO.class);
		request.setAttribute("spbList", baseDao.findMapList(sql, null));
		request.setAttribute("context", super.context);
		request.setAttribute("moduleid", moduleid);
		return "admin/pageCreate";
	}

	/**
	 * 保存模板
	 * 
	 * @param sTemplateBase
	 * @param request
	 * @param response
	 * @throws SQLException
	 * @throws ClassNotFoundException
	 */
	@RequestMapping(value = "savePage")
	public void saveSTemplateBase(
			@ModelAttribute("sPageBase") SPageBase sPageBase,
			HttpServletRequest request, HttpServletResponse response)
			throws SQLException, ClassNotFoundException {
		int flag = -1;
		Date currentTime = new Date();
		SimpleDateFormat formatter = new SimpleDateFormat("yyyy-MM-dd");
		String dateString = formatter.format(currentTime);
		sPageBase.setLastModifyDate(dateString);

		String sql = "insert into s_page_base  values(?,?,?,?,?)";
		JdbcBaseDAO baseDao = BeanUtils.getBean(JdbcBaseDAO.class);
		flag = baseDao.insert(sql, sPageBase.getPageId(), sPageBase
				.getPageName(), sPageBase.getPageMakeMode(), sPageBase
				.getTemplateId(), sPageBase.getLastModifyDate());
		if(sPageBase.getModuleId() != null && !"".equals(sPageBase.getModuleId())){
			String sql1 = "insert into s_module_page(module_id,page_id) values(?,?)";
			baseDao.insert(sql1, sPageBase.getModuleId(), sPageBase.getPageId());
		}
		Map<String, Object> map = new HashMap<String, Object>(1);
		map.put("flag", flag);
		List<STemplateParam> list = sTemplateParamService.queryWithCond(" where template_id=" + sPageBase.getTemplateId(),
				" order by param_sort ");
		/*String recordKey = sPageParamMainService.queryMaxKey();
		if(recordKey != null){
			int key = Integer.parseInt(recordKey);
			if(recordKey.startsWith("00")){
				if(key == 9999999){
					recordKey = "0"+(key+1);
				}else{
					recordKey = "00"+(key+1);
				}
			}else if(recordKey.startsWith("0")){
				if(key == 99999999){
					recordKey = (key+1)+"";
				}else{
					recordKey = "0"+(key+1);
				}
			}else{
				recordKey = (key+1)+"";
			}
		}else{
			recordKey = UUID.randomUUID().toString();
		}*/
		String recordKey = null;
		SPageParamMain pageParamMain = null;
		if(list != null){
			for(STemplateParam param : list){
				pageParamMain = new SPageParamMain();
				recordKey = UUID.randomUUID().toString().replaceAll("-", "");
				pageParamMain.setRecordKey(recordKey);
				pageParamMain.setPageId(sPageBase.getPageId());
				pageParamMain.setTemplateId(sPageBase.getTemplateId());
				pageParamMain.setTemplateParamType(param.getTemplateParamType());
				pageParamMain.setTemplateParamCode(param.getTemplateParamCode());
				pageParamMain.setTemplateParamName(param.getTemplateParamName());
				pageParamMain.setIsMustNeed(param.getIsMustNeed());
				pageParamMain.setParamValue(param.getTemplateParamDefvalue());
				pageParamMain.setParamRemarks(param.getParamRemarks());
				sPageParamMainService.insert(pageParamMain);
			}
		}
		String jsonResult = JSON.toJSONString(map);
		PrintWriter printWriter = null;
		try {
			printWriter = response.getWriter();
			printWriter.print(jsonResult);
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} finally {
			if (null != printWriter) {
				printWriter.flush();
				printWriter.close();
			}
		}

	}

	/**
	 * 删除页面
	 * 
	 * @param sTemplateBase
	 * @param request
	 * @param response
	 * @throws SQLException
	 * @throws ClassNotFoundException
	 */
	@RequestMapping(value = "deletePage")
	public void deletePage(HttpServletRequest request,
			HttpServletResponse response) throws SQLException,
			ClassNotFoundException {
		int flag = -1;
		String pageid = request.getParameter("page_id");

		String sql = "delete  from s_page_base  where page_id=?";
		String sql1 = "delete  from s_page_param_main  where page_id=?";
		String sql2 = "delete  from s_page_param_tag  where page_id=?";
		String sql3 = "delete  from s_page_param_trade_inout where trade_id in  (select trade_id from s_page_param_trade  where page_id=? )";
		String sql4 = "delete  from s_page_param_trade  where page_id=?";
		JdbcBaseDAO baseDao = BeanUtils.getBean(JdbcBaseDAO.class);
		flag = baseDao.delete(sql3, pageid);
		flag = baseDao.delete(sql4, pageid);
		flag = baseDao.delete(sql2, pageid);
		flag = baseDao.delete(sql1, pageid);
		flag = baseDao.delete(sql, pageid);
		Map<String, Object> map = new HashMap<String, Object>(1);
		map.put("flag", flag);
		String jsonResult = JSON.toJSONString(map);
		PrintWriter printWriter = null;
		try {
			printWriter = response.getWriter();
			printWriter.print(jsonResult);
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} finally {
			if (null != printWriter) {
				printWriter.flush();
				printWriter.close();
			}
		}

	}

	/**
	 * 制作制作（编辑）
	 * 
	 * @param request
	 * @return
	 * @throws Exception
	 */
	@RequestMapping(value = "edit")
	public String edit(HttpServletRequest request) throws Exception {

		// 取得传入页面标识
		String pageId = request.getParameter("page_id");
		if (StringUtils.isEmpty(pageId)) {
			throw new Exception("必须传入页面标识(pageId)参数!");
		}

		// 查询数据并放入到上下文中
		JdbcBaseDAO baseDao = BeanUtils.getBean(JdbcBaseDAO.class);
		SPageBase pageBase = baseDao.findBean(SPageBase.class,
				new Object[] { pageId });

		// 将数据上下文放到属性中
		request.setAttribute("SPageBase", pageBase);

		return "admin/pageEdit";
	}

	/**
	 * 页面基本信息编辑
	 * 
	 * @param request
	 * @return
	 * @throws Exception
	 */
	@RequestMapping(value = "baseInfoEdit")
	public String baseInfoEdit(HttpServletRequest request) throws Exception {

		// 取得传入页面标识
		String pageId = request.getParameter("page_id");
		if (StringUtils.isEmpty(pageId)) {
			throw new Exception("必须传入页面标识(pageId)参数!");
		}

		// 查询数据并放入到上下文中
		JdbcBaseDAO baseDao = BeanUtils.getBean(JdbcBaseDAO.class);
		SPageBase pageBase = baseDao.findBean(SPageBase.class,
				new Object[] { pageId });
		STemplateBase tempalte = baseDao.findBean(STemplateBase.class,
				new Object[] { pageBase.getTemplateId() });
		pageBase.setPageMakeMode(BeanUtils.getBean(DataDicService.class)
				.getValueText("PAGE_MAKE_MODE", pageBase.getPageMakeMode()));
		pageBase.setTemplateId(tempalte.getTemplateName());

		// 将数据上下文放到属性中
		request.setAttribute("SPageBase", pageBase);

		return "admin/pageBaseInfoEdit";
	}

	/**
	 * 页面所使用模板预览
	 * 
	 * @param request
	 * @return
	 * @throws Exception
	 */
	@RequestMapping(value = "templatePreview")
	public String templatePreview(HttpServletRequest request) throws Exception {

		// 取得传入模板标识
		String templateId = request.getParameter("template_id");
		if (StringUtils.isEmpty(templateId)) {
			throw new Exception("必须传入模板标识(templateId)参数!");
		}

		request.setAttribute("templateId", templateId);

		return "admin/pageTemplatePreview";
	}

	/**
	 * 页面所使用模板预览
	 * 
	 * @param request
	 * @return
	 * @throws Exception
	 */
	@RequestMapping(value = "templateParam")
	public String templateParam(HttpServletRequest request) throws Exception {

		// 获取所有参数
		super.getAllRequestData(request);

		// 取得传入模板标识
		String templateId = request.getParameter("page_id");
		if (StringUtils.isEmpty(templateId)) {
			throw new Exception("必须传入页面标识(page_id)参数!");
		}

		// 查询数据并放入到上下文中
		/*
		 * String sql = "select * from s_page_param_main where page_id=?";
		 * JdbcBaseDAO baseDao = BeanUtils.getBean(JdbcBaseDAO.class);
		 * super.context.addDataList("sppmList", baseDao.findMapList(sql,new
		 * Object[]{templateId}));
		 * 
		 * // 将数据上下文放到属性中 request.setAttribute("context", super.context);
		 */
		List<SPageParamMain> pageParamList = sPageParamMainService
				.queryByPageId(templateId);
		request.setAttribute("pageParamList", pageParamList);
		request.setAttribute("pageId", templateId);
		//查询是否有标签值
		/*int row = 0;
		int size = 0;
		row = (null == request.getParameter("pageNo") ? 0 : Integer
				.parseInt(request.getParameter("pageNo")));
		size = (null == request.getParameter("pageSize") ? 0 : Integer
				.parseInt(request.getParameter("pageSize")));

		FootPageDao fpd = new FootPageDao();
		FootPage fp = new FootPage();

		fp = fpd.querypage("  s_page_param_tag a  where    a.PAGE_ID= '"
				+ templateId + "'", row, size);
		row = (fp.getPageNo() - 1) * fp.getPageSize();*/

		String sql = "SELECT * FROM s_page_param_tag  a WHERE PAGE_ID='" + templateId+"' ";
		/*ITableModelDAO tableModelDao = (ITableModelDAO) BeanUtils
				.getBean("tableModelDAO");
		sql = tableModelDao.getNativePageSql(sql, row, fp.getPageSize());*/
		/*List<SPageParamTag> pageParamTagList = sPageParamTagService
				.queryByPageId(sql);*/
		Map<SPageParamMain, List<SPageParamTag>> tagMap = new HashMap<SPageParamMain, List<SPageParamTag>>();
		if(pageParamList != null && pageParamList.size() > 0){
			for(SPageParamMain spm :pageParamList){
				if("02".equals(spm.getTemplateParamType())){
					List<SPageParamTag> pageParamTagList = sPageParamTagService
						.queryByPageId(sql + " and template_param_code='" + spm.getTemplateParamCode() + "'");
					tagMap.put(spm, pageParamTagList);
				}
			}
		}
		request.setAttribute("tagmap", tagMap);
		//request.setAttribute("page", fp);
		//request.setAttribute("templateParamName", tagName);
		//查询是否有列表定义值
		/*int row2 = 0;
		int size2 = 0;
		row2 = (null == request.getParameter("pageNo") ? 0 : Integer
				.parseInt(request.getParameter("pageNo")));
		size2 = (null == request.getParameter("pageSize") ? 0 : Integer
				.parseInt(request.getParameter("pageSize")));

		FootPageDao fpd2 = new FootPageDao();
		FootPage fp2 = new FootPage();

		fp2 = fpd2.querypage("  s_page_param_trade a  where    a.PAGE_ID= '"
				+ templateId + "'", row2, size2);
		row2 = (fp2.getPageNo() - 1) * fp2.getPageSize();*/
		// 查询数据并放入到上下文中
		//String sql2 = "SELECT * FROM s_page_param_trade WHERE PAGE_ID=?";
		List<SPageParamTrade> tradeList = sPageParamTradeService.queryByPageId(templateId);
		/*super.context.addDataList("atpList", this.getTableModelDAO().queryList(
				sql2, new PageInfo(), new Object[] { templateId }));*/
		String tradName = "后台交易";
		if(pageParamList != null && pageParamList.size() > 0){
			for(SPageParamMain spm :pageParamList){
				if("03".equals(spm.getTemplateParamType())){
					tradName = spm.getTemplateParamName();
					break;
				}
			}
		}
		request.setAttribute("templateTradName", tradName);
		//request.setAttribute("context", super.context);
		request.setAttribute("tradelist", tradeList);
		return "admin/pageTemplateParam";
	}

}
